package com.pay.h5.service.impl;

import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.pay.constant.Constant;
import com.pay.entity.Merchant;
import com.pay.entity.Order;
import com.pay.h5.service.PayService;
import com.pay.service.IBaseInfoService;
import com.pay.service.IMerchantService;
import com.pay.service.IOrderService;
import com.pay.service.IProductService;
import com.pay.utils.FunctionUtils;
import com.pay.utils.GenerateOrderNoUtil;
import com.pay.utils.MD5Util;
import com.pay.utils.ResponseData;

import cn.hutool.core.util.StrUtil;

@Service
public class PayServiceImpl implements PayService{
	
	@Autowired
	private IMerchantService merchantService ;
	
	@Autowired
	private IProductService productService ;
	
	@Autowired
	private IOrderService orderService ;
	
	@Autowired
	private IBaseInfoService baseInfoService ;
	
	@Override
	public synchronized ResponseData doHandleGetway(Order order) {
		String channelSwitch = baseInfoService.getByKey(Constant.channelSwitch);
		if(!channelSwitch.equals("0")) {
			return ResponseData.baseError("无可用通道") ;
		}
		if(order.getMerchantId() == null) {
			return ResponseData.baseError("商户不存在") ;
		}
		Merchant merchant = merchantService.getById(order.getMerchantId());
		if(merchant == null) {
			return ResponseData.baseError("商户不存在") ;
		}
		if(merchant.getStatus() == Constant.merchant_invalid) {
			return ResponseData.baseError("商户未开通") ;
		}
		if(StrUtil.isBlank(order.getServicetype())) {
			return ResponseData.baseError("参数错误") ;
		}
		if(order.getAmount() == null || order.getAmount() <= 0) {
			return ResponseData.baseError("金额不能为空") ;
		}
		
		if(order.getServicetype().equals("Buy")) {
			//这里处理逻辑
			//怎么样怎么样的
		}else {
			return ResponseData.baseError("请求错误") ;
		}
		if(StrUtil.isBlank(order.getOrderno()) || order.getOrderno().length() < 6) {
			return ResponseData.baseError("商户订单号不能为空并且长度不得小于6位") ;
		}
		if("CNY".equals(order.getCurrency())) {
			//这里处理逻辑
			//怎么样怎么样的
		}else {
			return ResponseData.baseError("请求错误") ;
		}
		if(StrUtil.isBlank(order.getNotify())) {
			return ResponseData.baseError("回调地址必须填写") ;
		}
		if(StrUtil.isBlank(order.getType())) {
			return ResponseData.baseError("通道编码必须填写") ;
		}
		if(order.getNeedresponse() == null) {
			return ResponseData.baseError("必须填写是否需要回应 ") ;
		}
		if(StrUtil.isBlank(order.getSign())) {
			return ResponseData.baseError("签名错误") ;
		}
		
		if("alipaywap".equals(order.getType())) {
			
		}else if("alipayqr".equals(order.getType())) {
			return ResponseData.baseError("通道未开通") ;
		}else if("wxqr".equals(order.getType())) {
			return ResponseData.baseError("通道未开通") ;
		}else {
			return ResponseData.baseError("通道未找到") ;
		}
		
		//数字签名
		//String str=servicetype+partnerId+orderno+amount+currency+notify+type+ needresponse; 
		//String sign = MD5Util(MD5Util(str) + key) ;
		String str = order.getServicetype() + order.getMerchantId() + order.getOrderno() + order.getAmount() + order.getCurrency()
			+ order.getNotify() + order.getType() + order.getNeedresponse();
		String sign = MD5Util.md5Hex(MD5Util.md5Hex(str).toLowerCase() + merchant.getMerchantKey()).toLowerCase() ;
		if(!order.getSign().equals(sign)) {
			return ResponseData.baseError("签名错误") ;
		}
		/*String flagcode = productService.handleFlagcode();
		if(StrUtil.isBlank(flagcode)) {
			return ResponseData.baseError("服务器异常") ;
		}*/
		
		String platno = GenerateOrderNoUtil.gens("HD", 530L);
		order.setPlatno(platno);
		order.setFlagcode(platno);
		
		BigDecimal orderAmount = FunctionUtils.div(new BigDecimal(order.getAmount()), new BigDecimal(100), 2) ;
		BigDecimal reward = FunctionUtils.mul(merchant.getScale(), orderAmount, 2) ;
		long merchantAmount = FunctionUtils.mul(reward, new BigDecimal(100), 2).longValue() ;
		long taxAmount = order.getAmount() - merchantAmount ;
	
		order.setMerchantAmount(merchantAmount);
		order.setTaxAmount(taxAmount);
		boolean result = orderService.save(order);
		if(!result) {
			return ResponseData.baseError("创建订单失败") ;
		}
		
		String h5Domain = baseInfoService.getByKey(Constant.h5Domain);
		String linkURL = h5Domain + "/hdpay/toPay/" + order.getPlatno() ; 
		Map<String,Object> map = new HashMap<String,Object>() ;
		map.put("linkURL", linkURL) ;
		
		String url = h5Domain + "/hdpay/handlePay/" + platno ;
		String qrcode = "" ;
		try {
			qrcode = "https://render.alipay.com/p/s/i?scheme=" + URLEncoder.encode("alipays://platformapi/startapp?saId=10000007&clientVersion=3.7.0.0718&qrcode=", "UTF-8") + URLEncoder.encode(URLEncoder.encode(url, "UTF-8"), "UTF-8") ;
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		map.put("qrcode", qrcode) ;
		return ResponseData.build(200, "成功", map) ;
	}

}
